package com.mdp.oauth2.server.integration.authenticator;

import com.mdp.oauth2.server.LockUtil;
import com.mdp.oauth2.server.cache.SwitchUserTokenCacheService;
import com.mdp.oauth2.server.integration.IntegrationParams;
import com.mdp.oauth2.server.service.SysUserService;
import com.mdp.safe.client.dict.AuthType;
import com.mdp.safe.client.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClientResponseException;

import java.util.List;
import java.util.Optional;

/**
 * 免密切换用户
 * 格式 url: http://${domain}/api/m1/oauth2/oauth/token?grant_type=password&username=${username}&password=${前端密码MD5加密后的密码}&scope=all
 * @author chenyc
 * @date 2021-01-12
 **/
@Component
public class SwitchUserAuthenticator extends AuthenticatorAdapter{

    @Autowired
    SwitchUserTokenCacheService tokenCacheService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public User authenticate(IntegrationParams integrationParams) {
        User user= getByUserloginid(integrationParams.getUserloginid(),integrationParams);
        if(user!=null && "1".equals(user.get("locked"))) {
            String lockType = (String) user.get("lockType");
            String lockRemark = (String) user.get("lockRemark");
            String statusText = LockUtil.getLockMsgByLockType(lockType);
            if (!StringUtils.hasText(statusText)) {
                statusText = "lock-type-9 账户已锁定";
            }
            HttpHeaders httpHeaders = new HttpHeaders();
            throw new WebClientResponseException(401, statusText, httpHeaders, statusText.getBytes(), null, null);
        }
        return user;
    }

    /**
     * 查找用户基础信息
     * @param userid 前台登陆编号
     * @return
     */
    public User getByUserloginid(String userid,IntegrationParams integrationParams){
        User user=userBaseInfoQueryService.getUserByUserid(userid,integrationParams.getDatas());
        user.setPassword(passwordEncoder.encode(tokenCacheService.get(userid)));
        return user;
     }

    @Override
    public boolean supportAuthType(IntegrationParams integrationParams) {
        return AuthType.switch_user_by_token.name().equals(integrationParams.getAuthType());
    }
}
